package com.zh.demo04.login;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Map;

/**
 * 后台用户(即Admin端) Form登录 数据库获取用户信息
 * @author ZH
 * @Date 21:33 2020/4/18
 */
@AllArgsConstructor
@Slf4j
public class AdminUserDetailsService implements UserDetailsService {
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("【有人登录 Admin端】："+username);

        //数据库查询登录账号数据. 实际中从数据库查询.
        if (!user_table.containsKey(username)) throw new UsernameNotFoundException("账号不存在");

        String[] user = user_table.get(username);
        //生成Spring Security中登录用户的信息
        return new User(username, passwordEncoder.encode(user[1]), AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_"+user[2]));
    }

    //模拟数据库中的用户表
    static Map<String,String[]> user_table = Map.of(
            "admin",new String[]{"admin", "123456","ADMIN"},
            "guest",new String[]{"guest", "123456","USER"}
    );
}
